import dayjs from 'dayjs'
import common from '../store/common'

function eventLog(action, val) {
  if (action !== 'setProgressLen') {
    common.setEventLog(msgFormat(action, val))
  }
}

function msgFormat(action, val) {
  let actionMsg = ''
  let valMsg = ''
  let errMsg = '\n'
  try {
    actionMsg = `${action} emit ; `
    if (val) {
      valMsg = `val : ${legalVal(val)} --- ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`
    } else {
      valMsg = ''
    }
  } catch (e) {
    errMsg = `Error action=${action} val=${val}\n${e}`
  }
  // console.log(actionMsg + valMsg + errMsg)
  return actionMsg + valMsg + errMsg
}

function legalVal(val) {
  const type = val instanceof Object || val instanceof Array
  if (type) {
    try {
      return JSON.stringify(val)
    } catch (e) {
      return typeof val
    }
  } else {
    return JSON.stringify(val)
  }
}

export { eventLog }
